<?php
namespace App\Admin\Controllers\Consultation;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use App\Admin\Controllers\Common\Common;

class WorkOrderController extends Controller {
	public function index(Request $r) {
		return view("admin.consultation.consultation_list.work_order",[
			'st_id' => $r['st_id'],
			"Admins" => DB::table("admin_users")->where('dep',5)->get(['username','ch_name','en_name'])
		]);
	}

	public function getList(Request $r) {
		$rows = static::mkWhere($r->all())
			->limit($r['page']['pageSize'])
			->offset($r['page']['pageSize']*($r['page']['pageNumber']-1))
			->orderBy($r['sort']['sortBy'],$r['sort']['orderBy'])
			->getArr(['o.*','st.name as st_name','p.name as p_name']);
		return [
			'code' => 1,'msg' => "加载成功",
			'data' => [
				'total' => static::mkWhere($r->all())->count(),
				'rows' => $rows
			]
		];
	}

	private static function mkWhere($param) {
		$db = DB::table('consultation_workorder as o')
			->leftJoin('consultation_st as st','o.st_id','=','st.id')
			->leftJoin('consultation_parent as p','st.primary_parent_id','=','p.id');
		if($param['st_id']) {
			$db = $db->where('o.st_id','=',$param['st_id']);
		}
		if($param['admin_name']) {
			$db = $db->where('o.admin_name','=',$param['admin_name']);
		}
		if($param['st_name']) {
			$st_ids = DB::table('consultation_st')->where('name','like',"%".$param['st_name']."%")->pluck("id");
			$db = $db->whereIn('o.st_id','=',$st_ids);
		}
		if($param['phone']) {
			$db = $db->where('o.phone','like',"%".$param['phone']."%");
		}
		if($param['parent_name']) {
			$st_ids = DB::table('consultation_st as st')
				->leftJoin('consultation_parent_to_st as pts','st.id','=','pts.st_id')
				->leftJoin('consultation_parent as p','pts.p_id','=','p.id')
				->where('p.name',"like",'%'.$param['parent_name'].'%')
				->pluck("st.id")->toArray();
			$db = $db->whereIn('o.st_id',$st_ids);
		}
		if($param['ask_way']) {
			$db = $db->where('o.ask_way','=',$param['ask_way']);
		}
		if($param['ask_type']) {
			$db = $db->where('o.ask_type','=',$param['ask_type']);
		}
		if($param['ask_type_s']) {
			$db = $db->where('o.ask_type_s','=',$param['ask_type_s']);
		}
		if($param['date']) {
			$db = $db->whereBetween('o.date',[$param['date']." 00:00:00",$param['date']." 23:59:59"]);
		}
		return $db;
	}
}
